package com.bbs.detai1713.service;

import com.bbs.detai1713.dao.BoardMapper;
import com.bbs.detai1713.dao.FavoriteMapper;
import com.bbs.detai1713.dao.PostingMapper;
import com.bbs.detai1713.dao.UserMapper;
import com.bbs.detai1713.dao.entity.*;
import com.bbs.detai1713.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
@Transactional
public class DataService implements UserDetailsService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    BoardMapper boardMapper;
    @Autowired
    PostingMapper postingMapper;
    @Autowired
    FavoriteMapper favoriteMapper;
    @Value("${bbs.imagePath}")
    String imagePath;
    @Value("${bbs.imagePathReply}")
    String imagePathReply;

    //用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.loadUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("账户不存在");
        }
        user.setRole(userMapper.getUserRolesByRoleid(user.getRoleId()));
        System.out.println(user.getRole().toString());
        return user;
    }

    public boolean register(RegisterInformation registerInformation) {
        try {
            userMapper.register(registerInformation);
        } catch (Exception e) {
            log.debug("注册失败,e:{}", e);
            return false;
        }
        log.info("注册成功");
        return true;
    }

    public int updateInformation(UpdateInformation updateInformation) {
        return userMapper.updateInformation(updateInformation);
    }

    //板块操作
    public int createBoard(CreateBoard createBoard) {
        return boardMapper.createBoard(createBoard);
    }

    public List<TBoard> selectBoard(SelectBoard selectBoard) {
        return boardMapper.selectBoard(selectBoard);
    }

    public int deleteBoard(DeleteBoard deleteBoard) {
        return boardMapper.deleteBoard(deleteBoard);
    }

    public int updateBoard(UpdateBoard updateBoard) {
        return boardMapper.updateBoard(updateBoard);
    }

    //帖子操作
    public int countPosting(int boardId, int userId) {
        return postingMapper.countPosting(boardId, userId);
    }

    public long createPosting(CreatePosting createPosting) {
        createPosting.setCreateDate(new Date());
        postingMapper.createPosting(createPosting);
        postingMapper.createFloor(createPosting.getPostingId());
        return createPosting.getPostingId();
    }

    public int deletePosting(DeletePosting deletePosting) {

        return postingMapper.deletePosting(deletePosting);
    }

    public boolean deleteFloorPosting(DeleteFloorPosting deleteFloorPosting, long userId) {
        deleteFloorPosting.setUserId(userId);
        TPosting tPosting = postingMapper.selectPostingByPostingId((int) deleteFloorPosting.getPostingId());
        TSelectReplyByReplyId selectReplyByReplyId = postingMapper.selectReplyByReplyId(deleteFloorPosting.getReplyId());
        if (tPosting.getAuthorId() == userId || selectReplyByReplyId.getAuthorId() == userId) {//如果帖子是自己的或者是自己发的评论才能删除
            postingMapper.deleteFloorPosting(deleteFloorPosting);
            return true;
        }
        return false;
    }

    public int replyPosting(ReplyPosting replyPosting) {
        replyPosting.setReplyDate(new Date());
        replyPosting.setFloor(postingMapper.selectFloor(replyPosting.getPostingId()));
        int result = postingMapper.replyPosting(replyPosting);
        log.info("测试,{}", replyPosting.getPostingId());
        postingMapper.updateFloorUp1(replyPosting.getPostingId());
        return result;
    }

    public List<TPosting> selectPosting(SelectPosting selectedPosting) {
        return postingMapper.selectPosting(selectedPosting);
    }

    public int movePosting(MovePosting movePosting) {
        return postingMapper.movePosting(movePosting);
    }


    //收藏夹操作
    public List<TFavoriteList> selectFavorite(SelectFavorite selectFavorite) {
        return favoriteMapper.selectFavorite(selectFavorite);
    }

    public int addFavorite(AddFavorite addFavorite) {
        return favoriteMapper.addFavorite(addFavorite);
    }

    public List<TFavorite> selectFavoriteByPostingId(long userId, long postingId) {
        return favoriteMapper.selectFavoriteByPostingId(userId, postingId);
    }

    public int removeFavorite(RemoveFavorite removeFavorite) {
        return favoriteMapper.removeFavorite(removeFavorite);
    }

    public List<TReply> selectReply(int page, Integer postingId) {
        return postingMapper.selectReply(page, postingId);
    }

    public TPosting selectPostingByPostingId(Integer postingId) {
        return postingMapper.selectPostingByPostingId(postingId);
    }

    public int countReply(Integer postingId) {
        return postingMapper.countReply(postingId);
    }

    public List<TSelectUserReply> selectUserReply(long userId) {
        return postingMapper.selectUserReply(userId);
    }

    public List<TSelectOtherReply> selectOtherReply(long userId) {
        return postingMapper.selectOtherReply(userId);
    }

    //图片保存

    public String savePicByFormData(MultipartFile file, String userName) throws IOException {


        // 判断是否有路径
        if (!new File(imagePath).exists()) {
            new File(imagePath).mkdirs();
        }
        // 文件名为 time-userId.格式
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String[] after = file.getOriginalFilename().split("\\.");

//        for (int i = 0; i < after.length; i++) {
//            System.out.println(after[i].trim());
//        }
        log.info("文件格式为:{}", after[after.length - 1]);
        String fileName = df.format(t) + "-" + userName + "." + after[after.length - 1];
        File tempFile = new File(imagePath, fileName);

        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        log.info("图片保存路径为:{} {}", tempFile.getAbsolutePath(), tempFile.getCanonicalPath());
        file.transferTo(tempFile);
        return fileName;
    }

    public String savePicByFormDataReply(MultipartFile file, String userName) throws IOException {


        // 判断是否有路径
        if (!new File(imagePathReply).exists()) {
            new File(imagePathReply).mkdirs();
        }
        // 文件名为 time-userId.格式
        Date t = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String[] after = file.getOriginalFilename().split("\\.");

        log.info("文件格式为:{}", after[after.length - 1]);
        String fileName = df.format(t) + "-" + userName + "." + after[after.length - 1];
        File tempFile = new File(imagePathReply, fileName);

        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        log.info("图片保存路径为:{} {}", tempFile.getAbsolutePath(), tempFile.getCanonicalPath());
        file.transferTo(tempFile);
        return fileName;
    }
}
